package com.konsung.ksdc.manager.community;

import android.media.MediaRecorder;
import android.os.Environment;

import com.konsung.ksdc.R;
import com.konsung.ksdc.common.utils.FileUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;

import java.io.IOException;

/**
 * 声音检查
 */
public class SoundMeter {
    static final private double EMA_FILTER = 0.6;

    private MediaRecorder mRecorder = null;
    private double mEMA = 0.0;

    /**
     * 开始
     * @param name 名字
     */
    public void start(String name) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }

        try {
            if (mRecorder != null) {
                mRecorder.release();
                mRecorder = null;
            }
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setAudioChannels(1); // MONO
            mRecorder.setAudioSamplingRate(8000); // 8000Hz
            mRecorder.setAudioEncodingBitRate(64);

            mRecorder.setOutputFile(FileUtils.getSavePath(name));
            mRecorder.prepare();
            mRecorder.start();
        } catch (IOException e) {
            // 方便调试，此信息暂不删除
            ToastUtils.toastContent(MyApplication.getContext(), MyApplication.getContext()
                    .getString(R.string.chat_recorde_failed));
        }

    }

    /**
     * 停止
     * @param voiceName 声音名字
     */
    public void stop(String voiceName) {
        if(mRecorder != null){
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }

    /**
     * 开始
     */
    public void start() {
        if (mRecorder != null) {
            mRecorder.start();
        }
    }

    /**
     *
     * @return 返回振幅
     */
    public double getAmplitude() {
        if (mRecorder != null) {
            return (mRecorder.getMaxAmplitude() / 2700.0);
        } else {
            return 0;
        }
    }

}
